<?php
defined('BASEPATH') or exit('No direct script access allowed!');

class Project extends CI_Controller {
  function __construct() {
    parent::__construct();
    session_start();
    header('Content-Type: application/json');
    if(empty($_SESSION['login'])) {
      response('{status:"error",data:"Unauthorized"}', 401);
    }
    $this->load->model('MProject', 'mproject');
  }

  /* /api/project/(:any)     goes here */
  /* /api/project            goes here too */
  function index($hash = null) {
    switch($_SERVER['REQUEST_METHOD'])
    {
      case 'DELETE':
      case 'delete':
        if(empty($hash)) {
          response('{status:"error", data:"Invalid request!"}', 406);
        }
        $this->delete($hash);
        break;
      case 'PATCH':
      case 'patch':
        if(empty($hash)) {
          response('{status:"error", data:"Invalid request!"}', 406);
        }
        $this->patch($hash);
        break;
      case 'POST':
      case 'post':
        if(!empty($hash)) {
          response('{status:"error", data:"Invalid request"}', 406);
        }
        $this->post();
        break;
      case 'GET':
      case 'get':
        if(!empty($hash)) {
          $this->get($hash);
          break;
        }
        $this->getAll();
        break;
      default:
        response('{status:"error", data:"Method not support!"}', 405);
    }
  }

  private function patch($hash) {
    parse_str(file_get_contents('php://input'), $_PATCH);
    if(!isset($_PATCH['name'], $_PATCH['summary'], $_PATCH['tagColor'], $_PATCH['group'])) {
      response('{status:"error",data:"Invalid request data field!"}', 406);
    }
    echo json_encode($this->mproject->edit($hash, $_PATCH['name'], $_PATCH['summary'], $_PATCH['tagColor'], $_PATCH['group']));
  }

  private function delete($hash) {
    var_dump($this->mproject->delete($hash));
  }

  private function post() {
    if(!isset($_POST['name'], $_POST['summary'], $_POST['createdBy'], $_POST['tagColor'], $_POST['group'])) {
      response('{status:"error",data:"Invalid request data field!"}', 406);
    }
    echo json_encode($this->mproject->add($_POST['name'], $_POST['summary'], $_POST['tagColor'], $_POST['createdBy'], $_POST['group']));
  }

  private function getAll() {
    if(!isset($_SESSION['user']->group)) {
      response('{status:"error",data:"fatal error, user session data error at controller:project:75"}', 500);
    }
    echo json_encode($this->mproject->getAll($_SESSION['user']->group));
  }

  private function get($hash) {
    if(!isset($_SESSION['user']->group)) {
      response('{status:"error",data:"fatal error, user session data error at controller:project:85"}', 500);
    }
    echo json_encode($this->mproject->get($hash, $_SESSION['user']->group));
  }
}
